using System;

namespace CJ.XNFZ {
    public class TimeHelper : Singleton<TimeHelper> {
        public long startTime;
        public long endTime;
        public int usedTime;

        public long GetNow () {
            long time = ConvertDateTimeToLong (DateTime.UtcNow);
            return time;
        }

        public long SetStart () {
            startTime = ConvertDateTimeToLong (DateTime.UtcNow);
            endTime = startTime + 60000;
            usedTime = CountMinute (ConvertLongToDateTime (startTime), ConvertLongToDateTime (endTime));
            return startTime;
        }
        public long SetStop () {
            endTime = ConvertDateTimeToLong (DateTime.UtcNow);
            if (endTime < startTime) startTime = endTime - 60000;
            usedTime = CountMinute (ConvertLongToDateTime (startTime), ConvertLongToDateTime (endTime));
            return endTime;
        }
        public int GetUsedTime () {
            if (endTime < startTime) startTime = endTime - 60000;
            usedTime = CountMinute (ConvertLongToDateTime (startTime), ConvertLongToDateTime (endTime));
            return usedTime;
        }

        /// <summary>
        /// long-->datetime
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        protected DateTime ConvertLongToDateTime (long timeStamp) {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime (new DateTime (1970, 1, 1));
            long lTime = long.Parse (timeStamp / 1000 + "0000000");
            TimeSpan toNow = new TimeSpan (lTime);
            return dtStart.Add (toNow);
        }
        /// <summary>
        /// datetime-->long
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        protected long ConvertDateTimeToLong (DateTime time) {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime (new DateTime (1970, 1, 1));
            return (long) (time - startTime).TotalMilliseconds;
        }

        /// <summary>
        /// 计算差值（分钟）
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        protected int CountMinute (DateTime start, DateTime end) {
            int m = (end - start).Minutes;
            if (m < 1) m = 1;
            return m;
        }
    }
}